package com.hks360.car_treasure.activity;

import android.app.AlertDialog;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.hks360.car_treasure.R;
import com.hks360.car_treasure.common.AppConfig;
import com.hks360.car_treasure.common.BaiduMapConfig;
import com.hks360.car_treasure.common.Method;
import com.hks360.car_treasure.common.PrefKey;
import com.hks360.car_treasure.dialog.DateDialog;
import com.hks360.car_treasure.fragment.StrokeFragment;
import com.hks360.car_treasure.listener.TrakeLocationListener;
import com.hks360.car_treasure.model.JourneyLocation;
import com.hks360.car_treasure.socket.CommunicationManager;
import com.hks360.car_treasure.socket.PhoneBandDevice;
import com.hks360.car_treasure.trail.presenter.TrailPresenter;
import com.hks360.car_treasure.trail.presenter.TrailPresenterImpl;
import com.hks360.car_treasure.trail.view.TrailView;
import com.hks360.car_treasure.util.DateUtils;
import com.hks360.car_treasure.util.LogUtil;
import com.hks360.car_treasure.util.MyUtil;
import com.hks360.library.util.CommonUtil;
import com.hks360.library.util.PrefUtil;
import com.hks360.library.util.UIUtil;
import com.hks360.library.widget.CheckImageView;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.microedition.khronos.opengles.GL10;

/**
 * 行程Activity
 */
public class TrailActivity extends BaseActivity implements TrailView,BaiduMap.OnMapDrawFrameCallback {
    public static final int COUNT_DOWN = 0;
    public static final int UI_REFRESH = 1;
    private int startTime = 0;
    private int endTime = 0;
    private long interval = 100;
    private double speed = 100;
    private List<LatLng> points;
    private MapView mStrokeMv;
    private TrakeLocationListener mLocationListener;
    private TrailPresenter mPresenter;
    private BaiduMap mBaiduMap;
    private boolean isFirstLoc = true;
    private LocationClient mLocClient;
    private CheckImageView mMapPlusIv;
    private CheckImageView mMapMinusIv;
    private LocationClient locClient;
    private float mZoomLevel;
    private LinearLayout content;
    private LinearLayout trailList;
    private ImageButton btn_back;
    private ImageButton btn_search;
    private Button btn_search_start;
    private Button btn_search_end;
    private ImageButton btn_dev_list;
    private ImageButton btn_map;
    private EditText et_date_start;
    private EditText et_date_end;
    private TextView tv_confirm;
    private TextView tv_cancel;
    private AlertDialog adialog;
    private String year;
    private String month;
    private String day;
    private String hour;
    private String minute;
    private BDLocation location;
    private TrailPresenter mLocationPresenter;
    private List<LatLng> mpoints;

    private int count;
    private int i;
    private LatLng ll;
    private LatLng L1;
    private LatLng L2;
    private double middleX;
    private double middleY;
    private double startX;
    private double startY;
    private double endX;
    private double endY;
    private double dx;
    private double dy;
    private CountDownTimer cdt;
    private final static int GPS = 2;
    private String latitude;
    private String longitude;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case COUNT_DOWN:
                    L1 = new LatLng(middleX, middleY);
                    middleX = middleX + dx;
                    middleY = middleY + dy;
                    L2 = new LatLng(middleX, middleY);
                    drawLine(L1, L2);
                    break;
                case UI_REFRESH:
                    animationPlay();
                    break;
                case GPS:
                    latitude = "";
                    longitude = "";
                    latitude = AppConfig.mComManager.G_BYTE(mGps,9)*1000000 + AppConfig.mComManager.G_BYTE(mGps,10)*10000 + AppConfig.mComManager.G_BYTE(mGps,11)*100 + AppConfig.mComManager.G_BYTE(mGps,12)+"";
                    longitude = AppConfig.mComManager.G_BYTE(mGps,13)*1000000 + AppConfig.mComManager.G_BYTE(mGps,14)*10000 + AppConfig.mComManager.G_BYTE(mGps,15)*100 + AppConfig.mComManager.G_BYTE(mGps,16) + "";
                    Log.e("resp_result:","latitude==>" + latitude + ",longtitude==>" + longitude);
                    readCurrentLocationSuccess();
                    break;
            }
        }
    };
    private double mLatitude;
    private double mLongitude;
    LatLng mll;
    public void readCurrentLocationSuccess() {
        mLatitude = MyUtil.getBaiduLatitudeOrLongitude(latitude);
        mLongitude = MyUtil.getBaiduLatitudeOrLongitude(longitude);
        showLocation(mLatitude, mLongitude);
    }
    private void showLocation(double latitude, double longitude) {

        locClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(BaiduMapConfig.OPEN_GPS);// 打开gps
        option.setCoorType(BaiduMapConfig.COOR_TYPE); // 设置坐标类型
        option.setScanSpan(BaiduMapConfig.SCAN_SPAN);//设置坐标类型为bd09ll
        option.setPriority(LocationClientOption.NetWorkFirst);
        option.setProdName("locSDKDemo2");                      //设置产品线名称
        option.setScanSpan(5000);
        locClient.setLocOption(option);

        locClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                initCurrentLoaction();
            }
        });
        locClient.start();
        mll = new LatLng(latitude, longitude);
    }
    private void initCurrentLoaction() {
        if (mll.latitude != 0 && mll.longitude != 0) {
            CoordinateConverter converter = new CoordinateConverter();
            converter.from(CoordinateConverter.CoordType.GPS);
            // sourceLatLng待转换坐标
            converter.coord(mll);
            mll = converter.convert();
            LogUtil.d("latitude==>" + mll.latitude + ",longitude==>" + mll.longitude);
            try {
                mBaiduMap.setMyLocationEnabled(true);

                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(5)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(mll.latitude)
                        .longitude(mll.longitude).build();
                mBaiduMap.setMyLocationData(locData);
                locClient.stop();
                initZoom(mll.latitude, mll.longitude);
            } catch (Exception e) {
            }
        } else {
            try {
                initMyLocation();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    public void setupView() {
        mStrokeMv = (MapView) findViewById(R.id.stroke_mv);
        mMapPlusIv = (CheckImageView) findViewById(R.id.stroke_mapplus_iv);
        mMapMinusIv = (CheckImageView) findViewById(R.id.stroke_mapminus_iv);
        content = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_date_choose, null);
        trailList = (LinearLayout) findViewById(R.id.trail_list_layout);
        btn_back = (ImageButton) findViewById(R.id.trail_btn_back);
        btn_search = (ImageButton) findViewById(R.id.btn_search);
        btn_search_start = (Button) findViewById(R.id.btn_search_start);
        btn_search_end = (Button) findViewById(R.id.btn_search_end);
        btn_dev_list = (ImageButton) findViewById(R.id.btn_trail_list);
        btn_map = (ImageButton) findViewById(R.id.btn_full_map);
        et_date_start = UIUtil.findViewById(content, R.id.et_start);
        et_date_end = UIUtil.findViewById(content, R.id.et_overtime);
        tv_confirm = UIUtil.findViewById(content, R.id.tv_dialog_confirm);
        tv_cancel = UIUtil.findViewById(content, R.id.tv_dialog_cancel);
        mPresenter = new TrailPresenterImpl(this, this);
        mZoomLevel = PrefUtil.getFloat(this, PrefKey.ZOOM, BaiduMapConfig.ZOOM_BIG);
    }
    private byte[] mGps;
    @Override
    public void initData() {
        AppConfig.mComManager.getCarInfo(PrefUtil.getString(this,PrefKey.TBOX_ID,""));
        AppConfig.mComManager.setOnRecvCommunicationListener(new CommunicationManager.OnRecvCommunicationListener() {
            @Override
            public void onRecv_B001(int answerID, byte[] message) {

            }

            @Override
            public void onRecv_B601(String description) {

            }

            @Override
            public void onRecv_A602(List<String> llr) {

            }

            @Override
            public void onRecv_B500(byte[] message) {

            }

            @Override
            public void onRecv_B208(List<PhoneBandDevice> itemsDevices) {

            }

            @Override
            public void onRecv_CarStatus(byte[] carStatusBytes) {

            }

            @Override
            public void onRecv_Gps(byte[] gpsBytes) {
                mGps = gpsBytes;
                Log.e("RWQ", Arrays.toString(mGps));
                handler.sendEmptyMessage(GPS);
            }

            @Override
            public void onConnectBreak() {

            }

            @Override
            public void onRecv_B208Error() {

            }
        });
        mStrokeMv.showZoomControls(false);
        mBaiduMap = mStrokeMv.getMap();
        location = new BDLocation();
        mBaiduMap.setMyLocationEnabled(true);
    }

    private void initMyLocation() throws Exception {
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        if (locClient != null) {
            locClient.stop();
        }
        locClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);                                //打开gps
        option.setCoorType("bd0911");                           //设置坐标类型为bd09ll
        option.setPriority(LocationClientOption.NetWorkFirst);  //设置网络优先
        option.setProdName("locSDKDemo2");                      //设置产品线名称
        option.setScanSpan(5000);                               //定时定位，每隔5秒钟定位一次。
        locClient.setLocOption(option);
        locClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (bdLocation == null) {
                    return;
                }
                LogUtil.d(bdLocation.getLatitude() + "," + bdLocation.getLongitude());
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(0)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(bdLocation.getLatitude())
                        .longitude(bdLocation.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                ll = new LatLng(bdLocation.getLatitude(),
                        bdLocation.getLongitude());

                locClient.stop();
                initZoom(ll);
            }
        });
        locClient.start();
    }
    private void initZoom(double latitude, double longitude) throws Exception {
        LatLng ll = new LatLng(latitude, longitude);
        MapStatus.Builder builder = new MapStatus.Builder();
        LogUtil.e("mZoomLevel-->"+mZoomLevel+"");
        builder.target(ll).zoom(mZoomLevel);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    private void initZoom(LatLng ll) {
        MapStatus.Builder builder = new MapStatus.Builder();
        mZoomLevel = PrefUtil.getFloat(this, PrefKey.ZOOM, BaiduMapConfig.ZOOM_BIG);
        builder.target(ll).zoom(mZoomLevel);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    private void showDatePickDialog() {
        AlertDialog.Builder pdBuidler = new AlertDialog.Builder(this);
        if (adialog == null) {
            adialog = pdBuidler.setView(content).create();
        }
        adialog.show();
    }

    @Override
    public void addListener() {
        mMapPlusIv.setOnClickListener(this);
        mMapMinusIv.setOnClickListener(this);
        et_date_start.setOnClickListener(this);
        et_date_end.setOnClickListener(this);
        tv_confirm.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        btn_back.setOnClickListener(this);
        btn_search.setOnClickListener(this);
        btn_search_start.setOnClickListener(this);
        btn_search_end.setOnClickListener(this);
        btn_dev_list.setOnClickListener(this);
        btn_map.setOnClickListener(this);
    }

    @Override
    public void initView() {
        setContentView(R.layout.layout_trail);
        setupView();
        initDialog(R.string.loading_data);
        initData();
        addListener();
    }

    @Override
    public void onPause() {
        mStrokeMv.onPause();
        LogUtil.e("logtest1", "onpause");
        if (cdt != null) {
            cdt.cancel();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        mStrokeMv.onResume();
        LogUtil.e("logtest1", "onresume");
        super.onResume();
    }

    @Override
    public void onDestroy() {
        PrefUtil.putFloat(this, PrefKey.ZOOM, mZoomLevel);
        LogUtil.e("logtest1", "destory");
        mStrokeMv.onDestroy();
        super.onDestroy();
    }

    @Override
    public void viewClick(View v) {
        switch (v.getId()) {
            case R.id.stroke_mapplus_iv: //放大地图
                map_zoom_plus();
                break;
            case R.id.stroke_mapminus_iv:    //缩小地图
                map_zoom_minus();
                break;
            case R.id.trail_btn_back:    //返回
                finish();
                break;
            case R.id.btn_search_start:  //起始时间
                showDatePickDialog();
                break;
            case R.id.btn_search_end:  //截止时间
                showDatePickDialog();
                break;
            case R.id.btn_search:  //查找
                if (getTboxId() == "") {
                    Toast.makeText(this, "设备ID未绑定", Toast.LENGTH_LONG).show();
                }
                String date1 = et_date_start.getText().toString().trim();
                String date2 = et_date_end.getText().toString().trim();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    long time1 = format.parse(date1).getTime() / 1000;
                    long time2 = format.parse(date2).getTime() / 1000;
                    if (time2 < time1) {
                        CommonUtil.showToast(this, "结束时间应该大于起始时间");
                        return;
                    }
                    final String startTime = String.valueOf(time1);
                    final String endTime = String.valueOf(time2);
                    mPresenter.readJourneyLocation(1, startTime, endTime);
                } catch (Exception ex) {
                    LogUtil.e("logtest1", ex.getMessage().toString());
                }
                break;
            case R.id.btn_trail_list:  //列表
                trailList.setVisibility(View.GONE);
                map_zoom_divide();
                break;
            case R.id.btn_full_map:     //地图
                trailList.setVisibility(View.GONE);
                map_zoom_full();
                break;
            case R.id.et_start:
                queryTrack(et_date_start);
                break;
            case R.id.et_overtime:
                //// TODO: 2016/4/1   判断开始的时间应该大于结束的时间
                queryTrack(et_date_end);
                break;
            case R.id.tv_dialog_confirm:
//                btn_search_start.setText(et_date_start.getText().toString().trim());
//                btn_search_end.setText(et_date_end.getText().toString().trim());
                CommonUtil.showToast(this, "时间已选择完成");
                adialog.dismiss();
                break;
            case R.id.tv_dialog_cancel:
                adialog.dismiss();
                break;
        }
    }

    //test
    private float[] vertexs;
    private FloatBuffer vertexBuffer;

    public void onMapDrawFrame(GL10 gl, MapStatus drawingMapStatus) {
        if (mBaiduMap.getProjection() != null) {
            calPolylinePoint(drawingMapStatus);
            drawPolyline(gl, Color.argb(0, 255, 0, 0), vertexBuffer, 10, 3,
                    drawingMapStatus);
        }
    }

    public void calPolylinePoint(MapStatus mspStatus) {
        PointF[] polyPoints = new PointF[mpoints.size()];
        vertexs = new float[3 * mpoints.size()];
        int i = 0;
        for (LatLng xy : mpoints) {
            polyPoints[i] = mBaiduMap.getProjection().toOpenGLLocation(xy,
                    mspStatus);
            vertexs[i * 3] = polyPoints[i].x;
            vertexs[i * 3 + 1] = polyPoints[i].y;
            vertexs[i * 3 + 2] = 0.0f;
            i++;
        }
        for (int j = 0; j < vertexs.length; j++) {
            Log.d("RWQ", "vertexs[" + j + "]: " + vertexs[j]);
        }
        vertexBuffer = makeFloatBuffer(vertexs);
    }
    private void drawPolyline(GL10 gl, int color, FloatBuffer lineVertexBuffer,
                              float lineWidth, int pointSize, MapStatus drawingMapStatus) {
        gl.glEnable(GL10.GL_BLEND);
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

        gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

        float colorA = Color.alpha(color) / 255f;
        float colorR = Color.red(color) / 255f;
        float colorG = Color.green(color) / 255f;
        float colorB = Color.blue(color) / 255f;

        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, lineVertexBuffer);
        gl.glColor4f(colorR, colorG, colorB, colorA);
        gl.glLineWidth(lineWidth);
        gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, pointSize);

        gl.glDisable(GL10.GL_BLEND);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    }
    private FloatBuffer makeFloatBuffer(float[] fs) {
        ByteBuffer bb = ByteBuffer.allocateDirect(fs.length * 4);
        bb.order(ByteOrder.nativeOrder());
        FloatBuffer fb = bb.asFloatBuffer();
        fb.put(fs);
        fb.position(0);
        return fb;
    }
    private void animationPlay() {
        i = 0;
        locationMe(points.get(i).latitude,points.get(i).longitude);
    }

    //初始化动画放映的数据
    private void initDataPath() {
        try {
            startX = points.get(i).latitude;
            startY = points.get(i).longitude;
            endX = points.get(i + 1).latitude;
            endY = points.get(i + 1).longitude;
            middleX = startX;
            middleY = startY;
            count = points.size();
            dx = (endX - startX) / (speed - 1);
            dy = (endY - startY) / (speed - 1);
        } catch (Exception e) {
            return;
        }

    }

    //获取当前位置根据经纬度
    private void locationMe(double x, double y) {
        LatLng p = new LatLng(x, y);
        mBaiduMap.setMyLocationEnabled(true);
        MapStatus mMapStatus = new MapStatus.Builder().target(L1).zoom(mZoomLevel).build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        mBaiduMap.setMapStatus(mMapStatusUpdate);
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(5)
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(p.latitude)
                .longitude(p.longitude).build();
        mBaiduMap.setMyLocationData(locData);
        mBaiduMap.clear();
        initDataPath();
        cdt = new CountDownTimer(500, interval) {
            @Override
            public void onTick(long l) {
                handler.sendEmptyMessage(COUNT_DOWN);
            }

            @Override
            public void onFinish() {
                i++;
                if (i < count - 1) {
                    L1 = new LatLng(middleX, middleY);
                    initDataPath();
                    L2 = new LatLng(startX, startY);
                    drawLine(L1, L2);
                    cdt.start();
                }
            }
        }.start();

    }

    //两点划线
    private void drawLine(LatLng l1, LatLng l2) {
        mBaiduMap.setMyLocationEnabled(true);
        mStrokeMv.showZoomControls(true);
        MapStatus mMapStatus = new MapStatus.Builder().target(L1).zoom(mZoomLevel).build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        mBaiduMap.setMapStatus(mMapStatusUpdate);
        /*MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(p).zoom(mZoomLevel);*/
        //mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(5)
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(L1.latitude)
                .longitude(L1.longitude).build();
        mBaiduMap.setMyLocationData(locData);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 构造折线点坐标
        mpoints = new ArrayList<>();
        mpoints.add(l1);
        mpoints.add(l2);
        //构建分段颜色索引数组
        List<Integer> colors = new ArrayList<Integer>();
        colors.add(Integer.valueOf(Color.BLUE));
        OverlayOptions ooPolyline = new PolylineOptions().width(10)
                .colorsValues(colors).points(mpoints);
//        添加在地图中
        LogUtil.e("logtest1", L1.latitude + ",thisww" + L2.longitude);
        mBaiduMap.addOverlay(ooPolyline);
//        mBaiduMap.setOnMapDrawFrameCallback(this);

    }

    //放大地图
    private void map_zoom_plus() {
        mZoomLevel++;
        showZoom();
    }

    //缩小地图
    private void map_zoom_minus() {
        mZoomLevel--;
        showZoom();
    }

    //全屏地图
    private void map_zoom_full() {
        //mBaiduMap.clear();
        //mStrokeMv.updateViewLayout();
       /*  mStrokeMv = (Map) findViewById(R.id.stroke_mv);*/
        //mBaiduMap = mStrokeMv.getMap();
        //MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(ll);
        //mBaiduMap.animateMapStatus(msu);
        // showZoom();
    }

    //等分地图
    private void map_zoom_divide() {
        /*mZoomLevel = 0.5f;
        mBaiduMap.clear();
        mStrokeMv.buildDrawingCache();
        mBaiduMap = mStrokeMv.getMap();*/
        //mStrokeMv.onResume();
        //showZoom();
    }

    private void showZoom() {
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(mZoomLevel);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        zoom_image_status();
    }

    private void zoom_image_status() {
        if (mZoomLevel == mBaiduMap.getMinZoomLevel()) {
            mMapMinusIv.setEnabled(false);
        } else if (mZoomLevel == mBaiduMap.getMaxZoomLevel()) {
            mMapPlusIv.setEnabled(false);
        } else {
            mMapMinusIv.setEnabled(true);
            mMapPlusIv.setEnabled(true);
        }
    }

    /**
     * 轨迹查询(先选择日期，再根据是否纠偏，发送请求)
     */
    private void queryTrack(final EditText tvDatetime) {
        year = new String();
        month = new String();
        day = new String();
        hour = new String();
        minute = new String();
        // 选择日期
        String[] date = new String[5];
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;

        if (year.isEmpty() && month.isEmpty() && day.isEmpty()) {
            String curDate = DateUtils.getCurrentDate();
            date = DateUtils.getYMDArray(curDate, "-");
        }

        if (date != null) {
            year = date[0];
            month = date[1];
            day = date[2];
            hour = date[3];
            minute = date[4];
        }

        DateDialog dateDiolog = new DateDialog(this, new DateDialog.PriorityListener() {
            @Override
            public void refreshPriorityUI(String sltYear, String sltMonth, String sltDay, String slthour, String sltmin, DateDialog.CallBack back) {
                year = sltYear;
                month = sltMonth;
                day = sltDay;
                hour = slthour;
                minute = sltmin;
                back.execute();
            }
        }, new DateDialog.CallBack() {
            public void execute() {
                tvDatetime.setText(year + "-" + month + "-" + day + " " + hour + ":" + minute);
            }
        }, year, month, day, hour, minute, width, height, "选择日期", 1);
        Window window = dateDiolog.getWindow();
        window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置
        dateDiolog.setCancelable(true);
        dateDiolog.show();
    }

    @Override
    public String getTboxId() {
        return PrefUtil.getString(this, PrefKey.TBOX_ID, "");
    }

    @Override
    public void readJourneyLocationSuccess(List<JourneyLocation> journeyLocations) {
        if (journeyLocations != null && journeyLocations.size() > 0) {
            points = new ArrayList<>();
            for (JourneyLocation journeyLocation : journeyLocations) {
                LatLng mll;
                double latitude = Double.valueOf(journeyLocation.getLatitude())/1000000 ;
                double longitude = Double.valueOf(journeyLocation.getLongitude())/1000000;
                if(latitude == 0 || longitude == 0){
                    continue;
                }
                mll = new LatLng(latitude,longitude);
                CoordinateConverter converter = new CoordinateConverter();
                converter.from(CoordinateConverter.CoordType.GPS);
                // sourceLatLng待转换坐标
                converter.coord(mll);
                mll = converter.convert();
                Log.e("RWQ",mll.latitude + "," + mll.longitude);
                points.add(mll);
            }
            if (points.size() > 1) {
                handler.sendEmptyMessage(UI_REFRESH);
            }
        } else {
            Toast.makeText(this, "没有查到相关历史数据", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void readJourneyLocationFailed() {
        Toast.makeText(this, "获取历史数据失败", Toast.LENGTH_LONG).show();
    }

    @Override
    public void showLoading() {
        mDialog.show();
    }

    @Override
    public void hideLoading() {
        mDialog.dismiss();
    }

    @Override
    public void showToastMsg(String msg) {
        CommonUtil.showToast(this, msg);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }
}
